home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2009 February / PCWFEB09.iso / Software / Linux / Kubuntu 8.10 / kubuntu-8.10-desktop-i386.iso / casper / filesystem.squashfs / usr / share / hplip / testpage.py < prev    next >
Text File  |  2008-10-13  |  9KB  |  285 lines

  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. #
  4. # (c) Copyright 2003-2008 Hewlett-Packard Development Company, L.P.
  5. #
  6. # This program is free software; you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation; either version 2 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  19. #
  20. # Author: Don Welch
  21. #
  22.  
  23. __version__ = '5.1'
  24. __title__ = 'Testpage Print Utility'
  25. __doc__ = "Print a tespage to a printer. Prints a summary of device information and shows the printer's margins."
  26.  
  27.  
  28. # Std Lib
  29. import sys
  30. import os
  31. import getopt
  32. import re
  33. import time
  34.  
  35. # Local
  36. from base.g import *
  37. from base import device, utils, tui
  38. from prnt import cups
  39.  
  40. USAGE = [(__doc__, "", "name", True),
  41.          ("Usage: hp-testpage [PRINTER|DEVICE-URI] [OPTIONS]", "", "summary", True),
  42.          utils.USAGE_ARGS,
  43.          utils.USAGE_DEVICE,
  44.          utils.USAGE_PRINTER,
  45.          utils.USAGE_SPACE,
  46.          utils.USAGE_OPTIONS,
  47.          utils.USAGE_BUS1, utils.USAGE_BUS2,
  48.          ("Don't wait for printout to complete:", "-x", "option", True),
  49.          utils.USAGE_LOGGING1, utils.USAGE_LOGGING2, utils.USAGE_LOGGING3,
  50.          utils.USAGE_HELP,
  51.          utils.USAGE_SPACE,
  52.          utils.USAGE_NOTES,
  53.          utils.USAGE_STD_NOTES1, utils.USAGE_STD_NOTES2, 
  54.         ]
  55.  
  56. def usage(typ='text'):
  57.     if typ == 'text':
  58.         utils.log_title(__title__, __version__)
  59.  
  60.     utils.format_text(USAGE, typ, __title__, 'hp-testpage', __version__)
  61.     sys.exit(0)
  62.  
  63.  
  64. log.set_module('hp-testpage')
  65. try:
  66.     try:
  67.         opts, args = getopt.getopt(sys.argv[1:], 'p:d:hl:b:gx',
  68.                                    ['printer=', 'device=', 'help', 'help-rest', 
  69.                                     'help-man', 'logging=', 'bus=', 'help-desc'])
  70.     except getopt.GetoptError, e:
  71.         log.error(e.msg)
  72.         usage()
  73.  
  74.     printer_name = None
  75.     device_uri = None
  76.     bus = ['cups']
  77.     log_level = logger.DEFAULT_LOG_LEVEL
  78.     wait_for_printout = True
  79.  
  80.     if os.getenv("HPLIP_DEBUG"):
  81.         log.set_level('debug')
  82.  
  83.     for o, a in opts:
  84.         if o in ('-h', '--help'):
  85.             usage()
  86.  
  87.         elif o == '--help-rest':
  88.             usage('rest')
  89.  
  90.         elif o == '--help-man':
  91.             usage('man')
  92.  
  93.         elif o == '--help-desc':
  94.             print __doc__,
  95.             sys.exit(0)
  96.  
  97.         elif o in ('-p', '--printer'):
  98.             if a.startswith('*'):
  99.                 printer_name = cups.getDefaultPrinter()
  100.                 log.debug(printer_name)
  101.                 
  102.                 if printer_name is not None:
  103.                     log.info("Using CUPS default printer: %s" % printer_name)
  104.                 else:
  105.                     log.error("CUPS default printer is not set.")
  106.                 
  107.             else:
  108.                 printer_name = a
  109.  
  110.         elif o in ('-d', '--device'):
  111.             device_uri = a
  112.  
  113.         elif o in ('-b', '--bus'):
  114.             bus = [x.lower().strip() for x in a.split(',')]
  115.             if not device.validateBusList(bus):
  116.                 usage()
  117.  
  118.         elif o in ('-l', '--logging'):
  119.             log_level = a.lower().strip()
  120.             if not log.set_level(log_level):
  121.                 usage()
  122.  
  123.         elif o == '-g':
  124.             log.set_level('debug')
  125.  
  126.         elif o == '-x':
  127.             wait_for_printout = False
  128.  
  129.  
  130.     if device_uri and printer_name:
  131.         log.error("You may not specify both a printer (-p) and a device (-d).")
  132.         usage()
  133.  
  134.     utils.log_title(__title__, __version__)
  135.     
  136.     if os.getuid() == 0:
  137.         log.warn("hp-testpage should not be run as root.")
  138.  
  139.     if not device_uri and not printer_name:
  140.         try:
  141.             device_uri = device.getInteractiveDeviceURI(bus)
  142.             if device_uri is None:
  143.                 sys.exit(0)
  144.         except Error:
  145.             log.error("Error occured during interactive mode. Exiting.")
  146.             sys.exit(0)
  147.  
  148.     try:
  149.         d = device.Device(device_uri, printer_name)
  150.     except Error, e:
  151.         log.error("Device error (%s)." % e.msg)
  152.         sys.exit(1)
  153.  
  154.     if d.device_uri is None and printer_name:
  155.         log.error("Printer '%s' not found." % printer_name)
  156.         sys.exit(1)
  157.  
  158.     if d.device_uri is None and device_uri:
  159.         log.error("Malformed/invalid device-uri: %s" % device_uri)
  160.         sys.exit(1)
  161.  
  162.     user_cfg.last_used.device_uri = d.device_uri
  163.  
  164.     try:
  165.         try:
  166.             d.open()
  167.         except Error:
  168.             log.error("Unable to print to printer. Please check device and try again.")
  169.             sys.exit(1)
  170.  
  171.         if not printer_name:
  172.             if len(d.cups_printers) == 0:
  173.                 log.error("No printer queues found for device.")
  174.                 sys.exit(1)
  175.         
  176.             elif len(d.cups_printers) > 1:
  177.                 log.info("\nMultiple printers (queues) found in CUPS for device.")
  178.                 log.info(log.bold("\nPlease choose the printer (queue) to use for the test page:\n"))
  179.         
  180.                 max_name = 24
  181.                 for q in d.cups_printers:
  182.                     max_name = max(max_name, len(q))
  183.         
  184.                 formatter = utils.TextFormatter(
  185.                     (
  186.                         {'width': 4, 'margin': 2},
  187.                         {'width': max_name, 'margin': 2},
  188.                     )
  189.                 )
  190.         
  191.                 log.info(formatter.compose(("Num.", "CUPS printer (queue)")))
  192.                 log.info(formatter.compose(('-'*4, '-'*(max_name))))
  193.         
  194.                 x = 0
  195.                 for q in d.cups_printers:
  196.                     log.info(formatter.compose((str(x), d.cups_printers[x])))
  197.                     x += 1
  198.         
  199.                 ok, i = tui.enter_range("\nEnter number 0...%d for printer (q=quit) ?" % (x-1), 0, (x-1))
  200.                 if not ok: sys.exit(0)
  201.                 printer_name = d.cups_printers[i]
  202.         
  203.             else:
  204.                 printer_name = d.cups_printers[0]
  205.             
  206.         else:
  207.             if printer_name not in d.cups_printers:
  208.                 log.error("Invalid printer name: %s" % printer_name)
  209.                 sys.exit(1)
  210.  
  211.         log.info("")
  212.         
  213.         # TODO: Fix the wait for printout stuff... can't get device ID
  214.         # while hp: backend has device open in printing mode...
  215.         wait_for_printout = False
  216.         
  217.         if d.isIdleAndNoError():
  218.             d.close()
  219.             log.info( "Printing test page to printer %s..." % printer_name)
  220.             try:
  221.                 d.printTestPage(printer_name)
  222.             except Error, e:
  223.                 if e.opt == ERROR_NO_CUPS_QUEUE_FOUND_FOR_DEVICE:
  224.                     log.error("No CUPS queue found for device. Please install the printer in CUPS and try again.")
  225.                 else:
  226.                     log.error("An error occured (code=%d)." % e.opt)
  227.             else:
  228.                 if wait_for_printout:
  229.                     log.info("Test page has been sent to printer. Waiting for printout to complete...")
  230.  
  231.                     time.sleep(5)
  232.                     i = 0
  233.  
  234.                     while True:
  235.                         time.sleep(5)
  236.  
  237.                         try:
  238.                             d.queryDevice(quick=True)
  239.                         except Error, e:
  240.                             log.error("An error has occured.")
  241.  
  242.                         if d.error_state == ERROR_STATE_CLEAR:
  243.                             break
  244.  
  245.                         elif d.error_state == ERROR_STATE_ERROR:
  246.                             cleanup_spinner()
  247.                             log.error("An error has occured (code=%d). Please check the printer and try again." % d.status_code)
  248.                             break
  249.  
  250.                         elif d.error_state == ERROR_STATE_WARNING:
  251.                             cleanup_spinner()
  252.                             log.warning("There is a problem with the printer (code=%d). Please check the printer." % d.status_code)
  253.  
  254.                         else: # ERROR_STATE_BUSY
  255.                             update_spinner()
  256.  
  257.                         i += 1
  258.  
  259.                         if i > 24:  # 2min
  260.                             break
  261.  
  262.                     cleanup_spinner()
  263.  
  264.                 else:
  265.                     log.info("Test page has been sent to printer.")
  266.  
  267.         else:
  268.             log.error("Device is busy or in an error state. Please check device and try again.")
  269.             sys.exit(1)
  270.  
  271.  
  272.     finally:
  273.         d.close()
  274.  
  275.         log.info("")
  276.         log.notice("If an error occured, or the test page failed to print, refer to the HPLIP website")
  277.         log.notice("at: http://hplip.sourceforge.net for troubleshooting and support.")
  278.         log.info("")
  279.  
  280. except KeyboardInterrupt:
  281.     log.error("User exit")
  282.  
  283. log.info("")
  284. log.info("Done.")
  285.